package com.example.mq.demo.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

@Slf4j
@RocketMQTransactionListener(rocketMQTemplateBeanName = "customTxRocketMQTemplate")
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        log.info("执行本地事务 begin...");
        try {
            // 执行本地事务（如订单状态更新）
            boolean success = doLocalBusiness();
            return success ? RocketMQLocalTransactionState.COMMIT
                    : RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 回查本地事务状态（如查询数据库）
        boolean isCommitted = checkBusinessStatus(msg);
        return isCommitted ? RocketMQLocalTransactionState.COMMIT
                : RocketMQLocalTransactionState.ROLLBACK;
    }

    private boolean doLocalBusiness() {
        // 具体业务逻辑（需保证原子性）
        return true;
    }

    private boolean checkBusinessStatus(Message msg) {
        // 根据消息内容查询事务状态
        return true;
    }
}
